import { Form } from "antd";
import { Button, Checkbox, InputItem, List, Picker, TextareaItem, Toast, WhiteSpace, WingBlank } from "antd-mobile";
import { addon } from "pao-aop";
import { BaseReactElement, BaseReactElementControl, BaseReactElementState, reactControl } from "pao-aop-client";
import React from "react";
import { FileUploadBtn } from "src/business/components/buss-components/file-operation-btn/file-upload-btn";
import { request, setMainFormTitle } from "src/business/util_tool";
import { AppServiceUtility } from "src/projects/app/appService";
import { IntelligentElderlyCareAppStorage } from "src/projects/app/appStorage";
import { beforeUpload, ROUTE_PATH } from "src/projects/app/util-tool";
import { remote } from "src/projects/remote";
import { CharitableResult } from "../result";
import { SocietyInformation } from "../society-information";
const CheckboxItem = Checkbox.CheckboxItem;
/**
 * 组件：机构申请状态
 */
export interface CharitableOrganizationApplyViewState extends BaseReactElementState {
    // 申请人名字
    apply_name?: string;
    // 手机号码
    contacts?: string;
    // 银行卡号码
    account_number?: string;
    // 地址
    address?: string;
    // 受助描述
    description?: string;
    // 申请金额
    apply_money?: number;
    // 防止重复发送
    isSend?: boolean;
    // 是否多选
    multiple?: boolean;
    // 模板
    template_list?: any;
    template_id?: any;
    template_show_value?: any;
    // 模板的项目
    project_list?: any;
    // 临时储存，中间变量库
    database?: any;
    // 慈善会信息
    society_info?: any;
    // 是否展示结果页面
    isResult?: boolean;
}

const
    borderBoth = {
        borderTop: '1px solid #ddd',
        borderBottom: '1px solid #ddd',
    };
/**
 * 组件：机构申请
 * 机构申请
 */
export class CharitableOrganizationApplyView extends BaseReactElement<CharitableOrganizationApplyViewControl, CharitableOrganizationApplyViewState> {
    public database: any = {};
    constructor(props: any) {
        super(props);
        this.state = {
            apply_name: '',
            contacts: '',
            account_number: '',
            apply_money: 1,
            address: '',
            description: '',
            isSend: false,
            template_list: [],
            template_id: '',
            template_show_value: '',
            project_list: [],
            database: {},
            society_info: [],
            isResult: false,
        };
    }
    componentDidMount() {
        let user = IntelligentElderlyCareAppStorage.getCurrentUser();
        if (!user) {
            this.props.history!.push(ROUTE_PATH.login);
            return;
        }
        /** 获取申请模板 */
        let condition = { template_type: '慈善评估', template_name: '机构' };
        request(this, AppServiceUtility.assessment_template_service.get_assessment_template_list!(condition)!)
            .then((data: any) => {
                this.setState({
                    template_list: data.result
                });
            }).catch((error: Error) => {
                Toast.fail(error.message);
            });
        // 获取慈善会信息
        request(this, AppServiceUtility.charitable_service.get_charitable_society_list!({}, 1, 1))
            .then((data: any) => {
                if (data.result && data.result[0]) {
                    this.setState({
                        society_info: data.result[0] || [],
                    });
                }
            })
            .catch(error => {
                Toast.fail(error.message);
            });
    }
    changeValue = (e: any, inputName: any) => {
        this.setState({
            [inputName]: e
        });
    }
    handleSubmit = (): boolean => {
        const { apply_name, contacts, apply_money, account_number, address, description, template_id } = this.state;
        if (!apply_name) {
            Toast.fail('请输入机构名字', 1);
            return false;
        }
        if (!contacts) {
            Toast.fail('请输入联系方式', 1);
            return false;
        }
        if (!apply_money) {
            Toast.fail('请输入申请金额', 1);
            return false;
        }
        if (!account_number) {
            Toast.fail('请输入银行卡号码', 1);
            return false;
        }
        if (!address) {
            Toast.fail('请输入详细地址', 1);
            return false;
        }
        if (!description) {
            Toast.fail('请输入申请原因', 1);
            return false;
        }
        if (!template_id) {
            Toast.fail('请输入申请模板', 1);
            return false;
        }

        let projectData = this.getProjectData();
        if (projectData.status === '500') {
            Toast.fail(projectData.errMsg, 1);
            return false;
        }
        Toast.loading('Loading...', 3, () => {
            console.log('Load complete !!!');
        });
        var param: any = {
            apply_name: apply_name,
            contacts: contacts,
            apply_money: Number(apply_money),
            account_number: account_number,
            address: address,
            template: template_id,
            project_list: projectData.data || [],
            description: description || '',
            // 机构申请标识
            apply_type: '机构',
            // 必须登录标识
            need_login: true,
        };
        Toast.loading('Loading...', 11, () => {
        });
        let st = setTimeout(
            () => {
                Toast.hide();
                Toast.fail('提交失败，请稍候再试', 3);
            },
            10000
        );
        request(this, AppServiceUtility.charitable_service.update_charitable_recipient_apply!(param))
            .then((datas: any) => {
                console.log(datas);
                if (datas === 'Success') {
                    clearTimeout(st);
                    Toast.hide();
                    this.setState({
                        isResult: true,
                    });
                } else {
                    clearTimeout(st);
                    if (typeof (datas) === 'string') {
                        Toast.fail(datas);
                    } else {
                        Toast.fail('提交失败，请稍候再试', 3);
                    }
                }
            })
            .catch(error => {
                console.log(error);
                clearTimeout(st);
                Toast.fail('提交失败，请稍候再试', 3);
            });
        return false;
    }
    changeTemplate = (e: any) => {
        this.setState(
            {
                template_id: e[0],
                template_show_value: e,
            },
            () => {
                this.template_change(e[0]);
            });
    }
    /** 选择模板选择框值改变 */
    template_change = (value: any) => {
        console.log(value);
        request(this, AppServiceUtility.assessment_template_service.get_assessment_template_list!({ id: value }, 1, 99)!)
            .then((data: any) => {
                if (data.result) {
                    this.setState(
                        {
                            project_list: data.result,
                        },
                        () => {
                            this.getProjectList();
                        }
                    );
                }
            }).catch((error: Error) => {
                Toast.fail(error.message);
            });
    }
    getProjectData() {
        let database = this.state.database;
        let project_list: any = [];
        let errMsg = '';
        for (let i in database) {
            if (database[i]) {
                let item = database[i];
                console.log(item);
                if (item.origin_source.selete_type === '3' || item.origin_source.selete_type === '5') {
                    if (item.data_value === '') {
                        errMsg = `请输入${item.origin_source.project_name}`;
                        break;
                    }
                    project_list.push({
                        "ass_info": {
                            "project_name": item.origin_source.project_name,
                            "selete_type": item.origin_source.selete_type,
                            "value": item.data_value,
                        }
                    });
                } else if (item.origin_source.selete_type === '1' || item.origin_source.selete_type === '4' || item.origin_source.selete_type === '2') {
                    if (item.data_value === '') {
                        errMsg = `请选择${item.origin_source.project_name}`;
                        break;
                    }
                    project_list.push({
                        "ass_info": {
                            "project_name": item.origin_source.project_name,
                            "dataSource": item.origin_source.dataSource,
                            "selete_type": item.origin_source.selete_type,
                            "value": item.data_value,
                        }
                    });
                } else if (item.origin_source.selete_type === '6' || item.origin_source.selete_type === '7') {
                    if (item.file_data.length < 1) {
                        errMsg = `请上传${item.origin_source.project_name}`;
                        break;
                    }
                    project_list.push({
                        "ass_info": {
                            "project_name": item.origin_source.project_name,
                            "selete_type": item.origin_source.selete_type,
                            "value": item.file_data,
                        }
                    });
                }
            }
        }
        if (errMsg !== '') {
            return {
                status: '500',
                errMsg: errMsg,
            };
        }
        return {
            status: '200',
            data: project_list,
        };
    }
    setProjectData(e: any, index: number, type: string) {
        let database = this.state.database;
        if (type === "1" || type === "4") {
            // 单选和下拉是数组
            database[`ny${index}`].data_value = e[0];
            database[`ny${index}`].data_show_value = e;
        } else if (type === "3" || type === "5") {
            // 单行和多行直接储存
            database[`ny${index}`].data_value = e;
        } else if (type === "2") {
            // 多选
            let data_value = database[`ny${index}`].data_value;
            let new_data_value = [];
            let isDel = false;
            if (data_value.length > 0) {
                for (let i in data_value) {
                    if (data_value[i]) {
                        if (data_value[i] === Number(e)) {
                            isDel = true;
                            continue;
                        } else {
                            // 这里push的是序号！
                            new_data_value.push(data_value[i]);
                        }
                    }
                }
                if (isDel === false) {
                    new_data_value.push(Number(e));
                }
            } else {
                new_data_value.push(Number(e));
            }
            console.log(new_data_value);
            database[`ny${index}`].data_value = new_data_value;
        } else if (type === "6" || type === "7") {
            // 图片和文件直接储存
            database[`ny${index}`].file_data = e;
        }
        this.setState({
            database,
        });
    }
    getProjectList() {
        /** 用户选择的数组 */
        let project_list = this.state.project_list;
        if (project_list.length > 0) {
            let database = {};
            project_list!.forEach((item: any, index: number) => {
                if (item.hasOwnProperty("ass_info")) {
                    if (item.ass_info.hasOwnProperty("selete_type")) {
                        // 单选和下拉框，直接用select
                        if (item.ass_info.selete_type === "1" || item.ass_info.selete_type === "4") {
                            if (item.ass_info.hasOwnProperty("dataSource")) {
                                // 构造子数据集合
                                let select_child: any[] = [];
                                item.ass_info.dataSource.forEach((item: any) => {
                                    select_child.push({
                                        label: item.option_content,
                                        value: item.serial_number,
                                    });
                                });
                                database[`ny${index}`] = {
                                    origin_source: item.ass_info,
                                    // 数据源
                                    data_source: select_child,
                                    // 这个是储存的
                                    data_value: '',
                                    // 这个是显示的
                                    data_show_value: '',
                                };
                            }
                        } else if (item.ass_info.selete_type === "3") {
                            // 输入框
                            database[`ny${index}`] = {
                                origin_source: item.ass_info,
                                // 数据源
                                data_source: [],
                                // 这个是储存的
                                data_value: '',
                                // 这个是显示的
                                data_show_value: '',
                            };
                        } else if (item.ass_info.selete_type === "2") {
                            // 多选
                            // 构造子数据集合
                            let select_child: any[] = [];
                            item.ass_info.dataSource.forEach((item: any) => {
                                select_child.push({
                                    label: item.option_content,
                                    value: item.serial_number,
                                });
                            });
                            // 多选框
                            database[`ny${index}`] = {
                                origin_source: item.ass_info,
                                // 数据源
                                data_source: select_child,
                                // 这个是储存的
                                data_value: '',
                                // 这个是显示的
                                data_show_value: '',
                            };
                        } else if (item.ass_info.selete_type === "5") {
                            // 多行文本
                            database[`ny${index}`] = {
                                origin_source: item.ass_info,
                                // 数据源
                                data_source: [],
                                // 这个是储存的
                                data_value: '',
                                // 这个是显示的
                                data_show_value: '',
                            };
                        } else if (item.ass_info.selete_type === "6" || item.ass_info.selete_type === "7") {
                            // 多行文本
                            database[`ny${index}`] = {
                                origin_source: item.ass_info,
                                // 数据源
                                file_data: [],
                                // 这个是储存的
                                data_value: '',
                                // 这个是显示的
                                data_show_value: '',
                            };
                        }
                    }
                }
                return true;
            });
            this.setState({
                database,
            });
        }
    }
    onFileUploadChange(values: any) {
        console.log(values);
    }
    render() {
        setMainFormTitle("机构申请募捐");
        if (this.state.isResult === true) {
            return (
                <CharitableResult pprops={this.props} status="wait" title="提交成功，请等待审批" return_url={ROUTE_PATH.charitableRecipientApplyList} />
            );
        }
        const { getFieldDecorator } = this.props.form!;
        let template = this.state.template_list;
        let template_list: any[] = [];
        template!.map((item: any) => {
            template_list.push({
                label: item.template_name,
                value: item.id,
            });
        });
        const { template_show_value } = this.state;
        /** 用户选择的数组 */
        let project: any;
        let { project_list, database } = this.state;
        if (project_list.length > 0) {
            project = [];
            project_list!.forEach((item: any, index: number) => {
                if (item.hasOwnProperty("ass_info")) {
                    if (item.ass_info.hasOwnProperty("selete_type")) {
                        // 单选框，直接用select
                        if (item.ass_info.selete_type === "1" || item.ass_info.selete_type === "4") {
                            if (item.ass_info.hasOwnProperty("dataSource")) {
                                // 抑制报错
                                let data_source = database[`ny${index}`] && database[`ny${index}`]['data_source'] ? database[`ny${index}`]['data_source'] : [];
                                let data_show_value = database[`ny${index}`] && database[`ny${index}`]['data_show_value'] ? database[`ny${index}`]['data_show_value'] : '';
                                project.push(
                                    <List key={index} renderHeader={() => `请选择${item.ass_info.project_name}`}>
                                        <Picker data={data_source} cols={1} value={data_show_value} onChange={(e) => this.setProjectData(e, index, item.ass_info.selete_type)}>
                                            <List.Item arrow="horizontal" style={borderBoth}>{item.ass_info.project_name}</List.Item>
                                        </Picker>
                                    </List>
                                );
                            }
                        } else if (item.ass_info.selete_type === "3") {
                            // 输入框
                            project.push(
                                <List key={index} renderHeader={() => `请输入${item.ass_info.project_name}`}>
                                    <InputItem placeholder={`请输入${item.ass_info.project_name}`} onChange={(e) => this.setProjectData(e, index, item.ass_info.selete_type)} />
                                </List>
                            );
                        } else if (item.ass_info.selete_type === "2") {
                            let data_source = database[`ny${index}`] && database[`ny${index}`]['data_source'] ? database[`ny${index}`]['data_source'] : [];
                            // 多选
                            project.push(
                                <List key={index} renderHeader={() => `请选择${item.ass_info.project_name}`}>
                                    {data_source.map((itm: any, idx: number) => (
                                        <CheckboxItem key={idx} onChange={(e: any) => this.setProjectData(itm.value, index, item.ass_info.selete_type)}>
                                            {itm.label}
                                        </CheckboxItem>
                                    ))}
                                </List>
                            );
                        } else if (item.ass_info.selete_type === "5") {
                            // 多行文本
                            project.push(
                                <List key={index} renderHeader={() => `请输入${item.ass_info.project_name}`}>
                                    <TextareaItem placeholder={`请输入${item.ass_info.project_name}`} rows={3} autoHeight={true} onChange={(e) => this.setProjectData(e, index, item.ass_info.selete_type)} />
                                </List>
                            );
                        } else if (item.ass_info.selete_type === "6") {
                            let file_data = database[`ny${index}`] && database[`ny${index}`]['file_data'] ? database[`ny${index}`]['file_data'] : [];
                            // 图片
                            project.push(
                                <List key={index} renderHeader={() => `请上传${item.ass_info.project_name}`}>
                                    {getFieldDecorator(item.ass_info.project_name + '___6', {
                                        initialValue: file_data,
                                        rules: [{
                                            required: false,
                                        }],
                                    })(
                                        <FileUploadBtn list_type={"picture-card"} contents={"plus"} action={remote.upload_url} beforeUpload={beforeUpload} onChange={(e) => this.setProjectData(e, index, item.ass_info.selete_type)} />
                                    )}
                                </List>
                            );
                        } else if (item.ass_info.selete_type === "7") {
                            let file_data = database[`ny${index}`] && database[`ny${index}`]['file_data'] ? database[`ny${index}`]['file_data'] : [];
                            // 文件
                            project.push(
                                <List key={index} renderHeader={() => `请上传${item.ass_info.project_name}`}>
                                    {getFieldDecorator(item.ass_info.project_name + '___7', {
                                        initialValue: file_data,
                                        rules: [{
                                            required: false,
                                        }],
                                    })(
                                        <FileUploadBtn contents={"button"} action={remote.upload_url} onChange={(e) => this.setProjectData(e, index, item.ass_info.selete_type)} />
                                    )}
                                </List>
                            );
                        }
                    }
                }
                return null;
            });
        }
        const society_info = this.state.society_info;
        return (
            <div>
                <List renderHeader={() => '机构名字'}>
                    <InputItem clear={true} placeholder="请输入机构名字" onChange={(e) => this.changeValue(e, 'apply_name')} />
                </List>
                <List renderHeader={() => '联系方式'}>
                    <InputItem placeholder="请输入联系方式" onChange={(e) => this.changeValue(e, 'contacts')} />
                </List>
                <List renderHeader={() => '申请金额'}>
                    <InputItem placeholder="请输入申请金额" onChange={(e) => this.changeValue(e, 'apply_money')} />
                </List>
                <List renderHeader={() => '银行卡帐号'}>
                    <InputItem placeholder="请输入银行卡帐号" onChange={(e) => this.changeValue(e, 'account_number')} />
                </List>
                <List renderHeader={() => '详细地址'}>
                    <TextareaItem placeholder="请输入详细地址" rows={3} autoHeight={true} onChange={(e) => this.changeValue(e, 'address')} />
                </List>
                <List renderHeader={() => '申请原因'}>
                    <TextareaItem placeholder="请输入申请原因" rows={3} autoHeight={true} onChange={(e) => this.changeValue(e, 'description')} />
                </List>
                <List renderHeader={() => '选择申请模板'}>
                    <Picker data={template_list} cols={1} value={template_show_value} onChange={(e) => this.changeTemplate(e)}>
                        <List.Item arrow="horizontal" style={borderBoth}>申请模板</List.Item>
                    </Picker>
                </List>
                {project}
                <WhiteSpace size="lg" />
                <WhiteSpace size="lg" />
                <WingBlank size="lg">
                    <Button type="primary" onClick={this.handleSubmit}>提交申请</Button>
                </WingBlank>
                <WhiteSpace size="lg" />
                <WhiteSpace size="lg" />
                {society_info && society_info['id'] ? <SocietyInformation data_info={society_info} /> : null}
            </div>
        );
    }
}

/**
 * 控件：机构申请控制器
 * 机构申请
 */
@addon('CharitableOrganizationApplyView', '机构申请', '机构申请')
@reactControl(Form.create<any>()(CharitableOrganizationApplyView), true)
export class CharitableOrganizationApplyViewControl extends BaseReactElementControl {

}